package cn.ainit.sys.framework;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.sys.common.dao.Pagination;
import cn.ainit.sys.common.dao.SysBaseDao;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.framework.entity.ColnPerms;
import cn.ainit.sys.framework.entity.SysButtons;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.framework.save.StatementParamT;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.print.entity.SysPrint;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryJson;

@Transactional
@Repository("frameworkDao")
public class FrameworkDaoImpl extends SysBaseDao implements FrameworkDao {

	@Override
	public List<SysButtons> butnList(String butnId) throws Exception {
		String hql = "from SysButtons btn where btn.show = 'T' and btn.dsid = ? order by btn.orderNum";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, butnId);
		return (List<SysButtons>) query.list();
	}

	@Override
	public List<SysPrint> printList(String dsId) throws Exception {
		String hql = "from SysPrint sp where sp.id.dsId=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, dsId);
		return (List<SysPrint>) query.list();
	}

	@Override
	public List<SysColumns> colList(String colId, String flag) throws Exception {
		String hql = "";
		if (flag == null || flag.equals("")) {
			hql = "from SysColumns cln where cln.dsid = ? and cln.show='T' and cln.javaProperyRecourded is not null order by cln.orderNum,cln.groupId,cln.parentGroup";
		} else if (flag == "S" || flag.equals("S")) { // 如果为点击添加 传入S
			hql = "from SysColumns cln where cln.dsid = ? and cln.show='T' and cln.javaProperty is not null order by cln.orderNum,cln.groupId,cln.parentGroup";
		} else if (flag == "T" || flag.equals("T")) {
			hql = "from SysColumns cln where cln.dsid = ? and cln.firstPageFlag ='T' and show='T' order by cln.orderNum,cln.groupId,cln.parentGroup";
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, colId);
		return (List<SysColumns>) query.list();

	}

	@Override
	public Object queryRowsBySql(String sqlText) throws Exception {
		Object objects = null;
		try {
			SQLQuery query = this.getSessionFactory().getCurrentSession()
					.createSQLQuery(sqlText);
			objects = query.list();
			objects = this.getJdbcTemplate().queryForList(sqlText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return objects;
	}

	@Override
	public DataStore getDataStoreById(String dsid) throws Exception {
		String hql = " from DataStore ds where ds.dsId = ?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, dsid);
		List<DataStore> list = query.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public boolean updateObject(String sqlText, String[] valuesArr,
			String[] whereValue) throws Exception {
		return this.executeUpdateSql(sqlText, valuesArr, whereValue);
	}

	@Override
	public boolean execLink(String id, String otherParam) throws Exception {
		Connection conn = null;
		CallableStatement cs = null;
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			String sql = "{Call PK_BJ_XT.up_GetXtManage(?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1, id);
			cs.setString(2, otherParam);
			cs.execute();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return false;
	}

	@Override
	public String getMaxPkStr(String sql) throws Exception {
		return this.getPkStr(sql);
	}

	@Override
	public boolean saveObject(String sqlText, String[] valuesArr)
			throws Exception {
		return this.executeSqlValues(sqlText, valuesArr);
	}

	@Override
	public QueryJson queryRowsBySqlPagination(String sql, int cpage, int rows)
			throws Exception {
		QueryJson queryJson = new QueryJson();
		try {
			Pagination pagination = new Pagination(dbType, sql, cpage, rows,
					jdbcTemplate);
			queryJson.setTotal(pagination.getTotalRows());
			queryJson.setRows(pagination.getResultList());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return queryJson;
	}
	
	/**
	 * 用户获取所有界面字段
	 */
	@Override
	public List loadColumnsU(String colId, String type, String flag, String uid)
			throws Exception {
		List columns = new ArrayList();
		if (uid == null || uid.equals("")) {
			throw new RuntimeException("用户没有登录");
		}
		try {
			if (colId == null || colId.equals(""))
				throw new RuntimeException("DS_ID 传入有误");
			// 添加、详情界面
			String sql1 = "select DS_ID,WIDTH_ADD,HEIGHT_ADD,IS_PARENT_GROUP_ADD,GROUP_ID_ADD,ID_HIDDEN_GROUP_ADD,ORDER_NUM_ADD,COMMON_USE_ADD,HIDDEN_ADD,IS_SHOW_ADD,SINGLE_ROW_ADD,"
					+ "FORMAT_FUNC_ADD,DEFAULT_VALUE_ADD,INPUTTYPE_ADD,EDITYPE_ADD,READONLY_ADD,REQUIRED_ADD,PK_FORMAT_ADD,IS_PK_ADD,JAVA_CLASS,"
					+ "JAVA_PROPERTY,DG_WIDTH,DG_HEIGHT,IS_PROMPT,PROMPT_MSG,JAVA_PROPERTY_RECORDED,DS_ID,NAME,FORMAT_CONT,COLN_NAME,RELATION_FLAG,AUTO_ADD,AUTO_CONT_ADD,YUAN_DS_ID,"
					+ "IS_MULTI_CLNS,MULTI_CLNS_TABLE,RELATION_FUNC,RELATION_DSID,MULTI_CLNS_FK,IS_COPY,AFTER_VERIFY_M,MULTI_CLNS_VALUE,MULTI_CLNS_DESCRIB,MULTI_DESCRIB_FLAG,"
					+ "MULTI_DZ_DS_ID,NEW_LINE_ADD,SINGLE_MORE,MULTI_PROC_FUNC,DATALIST_FILTER,MULTI_RETURN_FUNC,MODEL_TYPE,DATALISTFUNC,MULTI_SAME_DS_ID,COLS_COUNT_ADD,ALIGN_ADD "
					+ " FROM SYS_COLUMNS  SC  WHERE  SC.DS_ID = '"
					+ colId
					+ "' "
					+ " AND ((SC.IS_SHOW_ADD = 'T' AND SC.JAVA_PROPERTY_RECORDED IS NOT NULL) "
					+ " OR (SC.IS_PARENT_GROUP_ADD = 'T')) ORDER BY SC.ORDER_NUM_ADD ";

			// 查询常用条件
			String sql6 = "select DS_ID,WIDTH_QR,HEIGHT_QR,IS_PARENT_GROUP_QR,GROUP_ID_QR,ID_HIDDEN_GROUP_QR,ORDER_NUM_QR,COMMON_USE_QR,HIDDEN_QR,IS_SHOW_QR,SINGLE_ROW_QR,FORMAT_FUNC_QR,"
					+ "DEFAULT_VALUE_QR,INPUTTYPE_QR,FORMAT_CONT,EDITYPE_QR,READONLY_QR,IS_COPY,REQUIRED_QR,JAVA_CLASS,JAVA_PROPERTY_RECORDED,INPUTTYPE_ADD,EDITYPE_ADD,"
					+ "JAVA_PROPERTY,DG_WIDTH,DG_HEIGHT,DS_ID,NAME,RELATION_FUNC,MULTI_PROC_FUNC,DATALIST_FILTER,DATALISTFUNC,relation_flag,"
					+ "RELATION_DSID,MULTI_DZ_DS_ID,WIDTH_QR,COLN_NAME,MULTI_SAME_DS_ID,MODEL_TYPE,COMMON_USE,SINGLE_MORE,ALIGN_QR "
					+ " FROM SYS_COLUMNS SC "
					+ " WHERE  SC.DS_ID = '"
					+ colId
					+ "' "
					+ " AND ((SC.IS_SHOW_QR = 'T' AND SC.JAVA_PROPERTY_RECORDED IS NOT NULL AND SC.COMMON_USE = 'T') "
					+ ") ORDER BY SC.ORDER_NUM_QR ";

			// 查询条件界面
			String sql3 = "select DS_ID,WIDTH_QR,HEIGHT_QR,DATALIST_FILTER,IS_PARENT_GROUP_QR,GROUP_ID_QR,ID_HIDDEN_GROUP_QR,ORDER_NUM_QR,COMMON_USE_QR,HIDDEN_QR,IS_SHOW_QR,SINGLE_ROW_QR,FORMAT_FUNC_QR,"
					+ "DEFAULT_VALUE_QR,DG_WIDTH,DG_HEIGHT,INPUTTYPE_QR,FORMAT_CONT,EDITYPE_QR,READONLY_QR,REQUIRED_QR,JAVA_CLASS,JAVA_PROPERTY_RECORDED,"
					+ "JAVA_PROPERTY,RELATION_FLAG,RELATION_FUNC,MULTI_PROC_FUNC,DATALISTFUNC,"
					+ "MULTI_DZ_DS_ID,RELATION_DSID,DS_ID,MULTI_SAME_DS_ID,MODEL_TYPE,NAME,COLN_NAME,"
					+ "NEW_LINE_QR,IS_COPY,SINGLE_MORE,EDITYPE_ADD,INPUTTYPE_ADD,COLS_COUNT_QR,ALIGN_QR "
					+ // _ADD用来做条件查询的时候判断
					" FROM SYS_COLUMNS SC WHERE  SC.DS_ID = '"
					+ colId
					+ "' "
					+ " AND ((SC.IS_SHOW_QR = 'T' AND SC.JAVA_PROPERTY_RECORDED IS NOT NULL) "
					+ " OR (SC.IS_PARENT_GROUP_QR = 'T')) ORDER BY SC.ORDER_NUM_QR ";

			// 列表界面
			String sql4 = " select DS_ID,ORDERNUM,READONLY,REQUIRED,DEFAULT_VALUE,X,Y,WIDTH,HEIGHT,FIRSTPAGEFLAG,SECPAGEFLAG,SINGLE_ROW,"
					+ " ISSHOW,RELATION_FUNC,USE_BEFORE_VALUE,CUSTOM_PROPS,JAVA_CLASS,"
					+ " JAVA_PROPERTY,DG_WIDTH,DG_HEIGHT,Default_Value_Qr,IS_OPEN_LOAD_SAME,MULTI_PROC_FUNC,DATALIST_FILTER,RELATION_DSID,MULTI_SAME_DS_ID,MODEL_TYPE,MULTI_DZ_DS_ID,OPEN_LOAD_TYPE,LOAD_INIT_DATA_FUN,MEMO,IS_PK,CONFIG,FORMAT_CONT,"
					+ " COMMON_USE,DS_ID,NAME,COLN_NAME,GROUP_NAME,PARENT_GROUP,GROUP_ID,GROUP_IS_OPEN,FORMAT,INPUTTYPE,EDITYPE,JAVA_PROPERTY_RECORDED,"
					+ " HIDDEN,STYLER,ONCLICK,ALIGN,"
					+ " EDITOR,"
					+ " IS_PK_ADD,ROW_STYLER,ROW_STYLER_GRADE,IS_COPY,FROZEN "
					+ " FROM SYS_COLUMNS SC  WHERE SC.DS_ID = '"
					+ colId
					+ "' "
					+ " AND (ISSHOW = 'T' AND JAVA_PROPERTY_RECORDED IS NOT NULL) ORDER BY ORDERNUM ";

			String sql7 = "SELECT * FROM SYS_COLUMNS WHERE DS_ID='" + colId
					+ "'";

			if (type != null && !type.equals("")) {
				if (type.equals("1") || type.equals("2") || type.equals("5")) {// 添加、查询、修改界面
					columns = this.getJdbcTemplate().queryForList(sql1);
				} else if (type.equals("3")) {// 查询条件界面
					columns = this.getJdbcTemplate().queryForList(sql3);
				} else if (type.equals("4") || type.equals("55")
						|| type.equals("44") || type.equals("77")
						|| type.equals("8")|| type.equals("9")||type.equals("99")) {// 查询界面
					columns = this.getJdbcTemplate().queryForList(sql4);
				} else if (type.equals("6")) {// 查询常用条件
					columns = this.getJdbcTemplate().queryForList(sql6);
				} else if (type.equals("7")) {
					columns = this.jdbcTemplate.queryForList(sql7);
				}else{
					System.out.println("#frameworkDaoImpl.loadColumnsU  type值不存在，请检查配置jquery.ainit-1.1.0.js 中的 producePage！！！！");
				}
			}
			this.getJdbcTemplate().queryForList(sql1);
		} catch (Exception e) {
			throw e;
		}
		return columns;
	}

	@Override
	public List<SysColumns> loadMulColumns(String dsId) throws Exception {
		String hql = "from SysColumns where dsid='" + dsId
				+ "' order by ordernum";
		List<SysColumns> list = new ArrayList<SysColumns>();
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		list = query.list();
		return list;
	}

	/***
	 * 根据DsID，和列名找到sysColumns
	 */
	@Override
	public SysColumns loadSysColumns(String dsid, String coluname)
			throws Exception {
		String hql = "from SysColumns where dsid='" + dsid
				+ "' and javaProperyRecourded='" + coluname + "'";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List list = query.list();
		if (list != null && !list.isEmpty()) {
			return (SysColumns) list.get(0);
		}
		return null;
	}

	@Override
	public List execSql(String sql) throws Exception {
		List list = new ArrayList();
		try {
			list = this.getJdbcTemplate().queryForList(sql);
			if (list != null) {
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String formatSql(String dsid, String sqlText, String uid)
			throws Exception {
		return this.formatDataSql(dsid, sqlText, uid);
	}

	@Override
	public String formatRowSql(String dsid, String sqlText, String uid)
			throws Exception {
		return this.formatRowDataSql(dsid, sqlText, uid);
	}

	@Override
	public List onlyOneCloumn(String colName, String dsId) throws Exception {
		List columns = new ArrayList();
		try {
			String sql = "SELECT * FROM SYS_COLUMNS S WHERE S.DS_ID='" + dsId
					+ "' AND S.NAME='" + colName + "'";
			columns = this.getJdbcTemplate().queryForList(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columns;
	}

	@Override
	public List lowerColumns(String lowFlag, String dsId) throws Exception {
		List columns = new ArrayList();
		try {
			String sql = "SELECT * FROM SYS_COLUMNS S WHERE upper(S.RELATION_FLAG) = upper('"
					+ lowFlag + "') AND S.DS_ID='" + dsId + "'";
			columns = this.getJdbcTemplate().queryForList(sql);
			if (columns != null) {
				return columns;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/***
	 * 设置默认值规则 defaultValue $uid $name $uid $depid $staid C- xx 常量 F- xx
	 * ORACLE方法 IN_VALUE P- xx ORACLE存储过程 IN_VALUE OUT_VALUE D- xxx 定制编号 F001
	 * 
	 * @param oldValues
	 *            原值
	 * @param clnName
	 *            字段名
	 * @param column
	 *            字段的参数
	 * @param clnTypeMap
	 *            所有字段数据库中的类型
	 * @param flag
	 *            false 为前台传入 true 为系统默认
	 * @return
	 * @author Xuzq
	 * @date 2014-4-28 下午03:24:26
	 */
	@Override
	public List queryDftRowByDsId(String flag, String dsid, HttpSession session)
			throws Exception {
		String sql = "";
		String defaultValName = "";
		if (flag.equals("1")) {
			sql = "SELECT T.NAME,T.DEFAULT_VALUE_ADD FROM SYS_COLUMNS t WHERE DS_ID = '"
					+ dsid + "' AND T.DEFAULT_VALUE_ADD IS NOT NULL";
			defaultValName = "DEFAULT_VALUE_ADD";
		} else if (flag.equals("2")) {
			sql = "SELECT T.NAME,T.Default_Value_Qr FROM SYS_COLUMNS t WHERE DS_ID =  '"
					+ dsid + "' AND T.Default_Value_Qr IS NOT NULL";
			defaultValName = "DEFAULT_VALUE_QR";
		} else {
			System.out
					.println("error  #FrameworkDaoImpl   318 加载默认值的标志位 flag 传入有误");
		}
		List<Map<String, Object>> columnsMap = this.getJdbcTemplate()
				.queryForList(sql);
		Object defaultValue = "";
		String nameValue = "";
		String dValue = "";
		StatementParamT sparam = new StatementParamT();
		sparam.getSql().append(" select ");
		for (int i = 0; i < columnsMap.size(); i++) {
			defaultValue = columnsMap.get(i).get(defaultValName);
			nameValue = columnsMap.get(i).get("NAME").toString();
			if (defaultValue != null && !"".equals(defaultValue.toString())) {
				if (defaultValue.toString().indexOf("$") == 0
						|| defaultValue.toString().indexOf("C") == 0
						|| defaultValue.toString().indexOf("F") == 0) {
					// $uid (传入的值：uid) $date+30 (传入的值：date+30) 时间推迟30天
					// C-1(传入的值：-1) F-syspring.xxx (传入的值：-syspring.xxx)
					dValue = formatShowDef(defaultValue.toString().substring(1,
							defaultValue.toString().length()), session, dsid);
					if (defaultValue.toString().substring(1,
							defaultValue.toString().length()).indexOf("date") == 0) {
						sparam.getSql().append(
								" " + dValue + " " + nameValue + ","); // 如果是时间
																		// 就不要单引号
					} else if (defaultValue.toString().indexOf("F") == 0) {
						sparam.getSql().append(
								" " + dValue + " " + nameValue + ","); // 如果是方法
																		// 例：springmc.bj_yz()
																		// 就不要单引号
					} else {
						sparam.getSql().append(
								"'" + dValue + "' " + nameValue + ",");
					}
				}
			}
		}
		if (!(sparam.getSql().lastIndexOf(",") > 0)) {
			return new ArrayList();
		}
		String valueSql = sparam.getSql().substring(0,
				sparam.getSql().lastIndexOf(","))
				+ " from dual";
		List<Map<String, Object>> values = this.getJdbcTemplate().queryForList(
				valueSql);
		return values;
	}

	// $uid $name $depid $staid
	// * $data //获取界面默认值，只有放入session和时间的可以获取
	// $uid (传入的值：uid) $date+30 (传入的值：date+30) 时间推迟30天
	// C-1(传入的值：-1) F-syspring.xxx (传入的值：-syspring.xxx)
	public String formatShowDef(String valueflag, HttpSession session,
			String dsid) {
		Object afvalue = "";
		if ("uid".equals(valueflag.trim())) {
			afvalue = session.getAttribute(SessionCont.uid);
		} else if ("name".equals(valueflag.trim())) {
			afvalue = session.getAttribute(SessionCont.name);
		} else if ("depid".equals(valueflag.trim())) {
			afvalue = session.getAttribute(SessionCont.DEPART_ID);
		} else if ("staid".equals(valueflag.trim())) {
			afvalue = session.getAttribute(SessionCont.STATION_ID);
		} else if ("date".equals(valueflag.trim())) {
			afvalue = System.currentTimeMillis() / 1000 * 1000 + "";
		} else if (valueflag.trim().indexOf("date+") == 0) {
			afvalue = System.currentTimeMillis() / 1000 * 1000 + "";
			afvalue = (Long.parseLong(afvalue.toString()) + Long
					.parseLong(valueflag.trim().substring(5,
							valueflag.trim().length())) * 24 * 3600 * 1000)
					+ "";
		} else if (valueflag.trim().indexOf("date-") == 0) {
			afvalue = (System.currentTimeMillis() / 1000 * 1000 - Long
					.parseLong(valueflag.trim().substring(5,
							valueflag.trim().length())) * 24 * 3600 * 1000)
					+ "";
		} else {
			if (valueflag.indexOf("-") == 0) {
				afvalue = valueflag.substring(1);
				// 注意：取存储过程名不能包含关键单词：如： uid name depid staid date
				// F-sysSpringmc.Pk_uf(uid,dsid,depid)
				if (afvalue != null && !"".equals(afvalue.toString())) {
					afvalue = afvalue.toString().replace("dsid",
							"'" + dsid + "'");
					afvalue = afvalue.toString().replace(
							"uid",
							"'"
									+ session.getAttribute(SessionCont.uid)
											.toString() + "'");
					afvalue = afvalue.toString().replace(
							"name",
							"'"
									+ session.getAttribute(SessionCont.name)
											.toString() + "'");
					afvalue = afvalue.toString().replace(
							"depid",
							"'"
									+ session.getAttribute(
											SessionCont.DEPART_ID).toString()
									+ "'");
					afvalue = afvalue.toString().replace(
							"staid",
							"'"
									+ session.getAttribute(
											SessionCont.STATION_ID).toString()
									+ "'");
				}
			}
		}
		return afvalue == null ? "" : afvalue.toString();
	}

	@Override
	public String execSqlForString(String sql) throws Exception {
		String strValue = "";
		try {
			strValue = jdbcTemplate.queryForObject(sql, String.class);
			if (!"".equals(strValue)) {
				return strValue;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public SysDzSource sqlForList(String sql) throws Exception {
		SysDzSource dzSource = new SysDzSource();
		try {
			List<Map<String, Object>> list = this.getJdbcTemplate()
					.queryForList(sql);
			if (list == null) {
				return null;
			}
			if (list.size() > 1) {
				throw new RuntimeException("查询时，出现两条对照信息，请检查！");
			}
			Map<String, Object> valueMap = list.get(0);
			if (valueMap.get("SQL_TEXT") == null
					|| valueMap.get("SHOW_NAME") == null
					|| valueMap.get("SHOW_PK") == null) {
				throw new RuntimeException("sqlText或者showName或者showPk为Null");
			}
			dzSource.setSqlText(valueMap.get("SQL_TEXT").toString());
			dzSource.setShowName(valueMap.get("SHOW_NAME").toString());
			dzSource.setShowPk(valueMap.get("SHOW_PK").toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dzSource;
	}

	@Override
	public List getMultiList(String dsId, String sinPkVal, String colName,
			String param1) throws Exception {
		List list = new ArrayList();
		try {
			String sql1 = "select s.update_table from sys_datastore  s where s.ds_id='"
					+ param1 + "'";
			String sql2 = "select s.MULTI_CLNS_FK from sys_columns s where s.ds_id='"
					+ dsId + "' and s.name='" + colName + "'";
			String mulTable = this.jdbcTemplate.queryForObject(sql1,
					String.class);
			String sinPk = this.jdbcTemplate.queryForObject(sql2, String.class);
			if (mulTable != null && mulTable != "") {
				String mulSql = "select * from " + mulTable + " where " + sinPk
						+ " ='" + sinPkVal + "'";
				list = this.jdbcTemplate.queryForList(mulSql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String newSourceId(String dsId, String colName, String oldSourceId)
			throws Exception {
		Connection conn = null;
		CallableStatement cs = null;
		String newSouceId = "";
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			String sql = "{Call PK_SYS.up_CopyMulitiDZ(?,?,?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1, dsId);
			cs.setString(2, colName);
			cs.setString(3, oldSourceId);
			cs.registerOutParameter(4, Types.VARCHAR);
			cs.execute();
			newSouceId = cs.getString(4);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return newSouceId;
	}

	@Override
	public SysColumns queryColumnsMul(String dsid, String clnName)
			throws Exception {
		String sql = "select MULTI_CLNS_TABLE," + "MULTI_CLNS_FK,"
				+ "MULTI_CLNS_VALUE,"
				+ "MULTI_DZ_DS_ID,MULTI_SAME_DS_ID,EDITYPE from sys_columns "
				+ " where ds_id = '" + dsid + "' and name = '" + clnName + "'";
		List<Map<String, Object>> list = this.getJdbcTemplate().queryForList(
				sql);
		SysColumns tmpColumns = new SysColumns();
		if (list != null && !list.isEmpty()) {
			tmpColumns.setMultiClnsTable(list.get(0).get("MULTI_CLNS_TABLE")
					.toString());
			tmpColumns.setMultiClnsFk(list.get(0).get("MULTI_CLNS_FK")
					.toString());
			tmpColumns.setMultiClnsDValue(list.get(0).get("MULTI_CLNS_VALUE")
					.toString());
			tmpColumns.setMultiDzDsId(list.get(0).get("MULTI_DZ_DS_ID")
					.toString());
			tmpColumns.setEdiType(list.get(0).get("EDITYPE").toString());
		}
		return tmpColumns;
	}

	@Override
	public SysDzSource loadDzSource(String dzId) throws Exception {
		return (SysDzSource) this.getSessionFactory().getCurrentSession().load(
				SysDzSource.class, dzId);
	}

	/***
	 * 根据单据id,判断单据是否设置修改的权限设置
	 * 
	 * @param djId
	 * @param param
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-4-7 下午04:15:37 
	 */
	@Override
	public String dbcModifyPerms(String djId, String dsId, HttpSession session,
			String param) throws Exception {
		Connection conn = null;
		CallableStatement cs = null;
		String isModify = null;
		try {
			conn = this.jdbcTemplate.getDataSource().getConnection();
			String sql = "{Call PK_MODIFY_PERMS.UP_PREMS_MODIFY_DJ(?,?,?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1, djId);
			cs.setString(2, dsId);
			System.out.println((String) session.getAttribute(SessionCont.uid));
			cs.setString(3, (String) session.getAttribute(SessionCont.uid));
			cs.registerOutParameter(4, Types.VARCHAR);
			cs.execute();
			isModify = cs.getString(4);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return isModify;
	}

	/***
	 * 根据单据id,判断单据是否设置列修改的权限设置
	 * 
	 * @param djId
	 * @param param
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-4-7 下午04:15:37 
	 */
	@Override
	public ColnPerms dbcModifyColnPerms(String djId, String dsId,
			HttpSession session, String param) throws Exception {
		Connection conn = null;
		CallableStatement cs = null;
		ColnPerms colnPerms = new ColnPerms();
		try {
			conn = this.jdbcTemplate.getDataSource().getConnection();
			String sql = "{Call PK_MODIFY_PERMS.UP_PREMS_MODIFY_COLN(?,?,?,?,?,?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1, djId == null ? "" : djId);
			cs.setString(2, dsId);
			cs.setString(3, (String) session.getAttribute(SessionCont.uid));
			cs.registerOutParameter(4, Types.VARCHAR);
			cs.registerOutParameter(5, Types.VARCHAR);
			cs.registerOutParameter(6, Types.VARCHAR);
			cs.registerOutParameter(7, Types.VARCHAR);
			cs.execute();
			colnPerms.setOwnpermsColns(cs.getString(4));
			colnPerms.setNonePermsColns(cs.getString(5));
			colnPerms.setBeforeVMcolns(cs.getString(6));
			colnPerms.setKeepMColns(cs.getString(7));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return colnPerms;
	}

	@Override
	public Map loadRightList(String funcId, String uid) throws Exception {
		Connection conn=null;
		CallableStatement cs=null;
		ResultSet norListButns = null;
		Map list=new HashMap();
		try {
			conn=this.getJdbcTemplate().getDataSource().getConnection();
			String callName = "{Call PK_RIGHT_FUNC.UP_GetGridRIGHT(?,?,?)}";
			cs=conn.prepareCall(callName);
			cs.setString(1,funcId);
			cs.setString(2,uid);
			cs.registerOutParameter(3, Types.VARCHAR);
			cs.execute();
			list.put("canEditButns",cs.getString(3));
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(cs!=null){
				cs.close();
			}
			if(conn!=null){
				conn.close();
			}
		}
		return list;
	}
	
	
	@Override
	public Map<String, List> loadAInfoList(String funcId, String uid,String djId)
			throws Exception {
		System.out.println("===============详情界面调用 PK_RIGHT_FUNC.UP_GetDetailRIGHT的参数值： funcId："+funcId+"==uid:"+uid+"==djId:"+djId);
		Connection conn=null;
		CallableStatement cs=null;
		ResultSet norListButns = null;
		Map list=new HashMap();
		try {
			conn=this.getJdbcTemplate().getDataSource().getConnection();
			String callName = "{Call PK_RIGHT_FUNC.UP_GetDetailRIGHT(?,?,?,?,?,?)}";
			cs=conn.prepareCall(callName);
			cs.setString(1,funcId);
			cs.setString(2,uid);
			cs.setString(3,djId);
			cs.registerOutParameter(4,Types.VARCHAR);
			cs.registerOutParameter(5,Types.VARCHAR);
			cs.registerOutParameter(6,Types.VARCHAR);
			cs.execute();
			list.put("ownAinfoButns",cs.getString(4));    //有权限的按钮
			list.put("editAinfoButns",cs.getString(5));   //有权限并且可点击的按钮
			list.put("isRColn",cs.getString(6));		  //字段权限 和数据权限
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(cs!=null){
				cs.close();
			}
			if(conn!=null){
				conn.close();
			}
		}
		return list;
	}
	
	/****
	 * 把调用数据库返回的游标转换成List 结果集
	 * @param rs
	 * @return
	 * @author feifei
	 * @date: 2015-5-12 下午03:54:40 
	 */
	public List returnCursor(ResultSet rs){
		List list=new ArrayList();
		try {
			ResultSetMetaData md = rs.getMetaData();  
			int columnCount = md.getColumnCount();
			while (rs.next()) { 
				Map rowData = new HashMap(); 
				for (int i = 1; i <= columnCount; i++) {  
					rowData.put(md.getColumnName(i),rs.getObject(i));  
				}
				list.add(rowData);  
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String execQueryConditionSql(String dsId, String uid) {
		Connection conn = null;
		CallableStatement cs = null;
		try {
			conn = this.jdbcTemplate.getDataSource().getConnection();
			String sql = "{Call pk_right.UP_GetDataRight(?,?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1, uid);
			cs.setString(2, dsId);
			cs.registerOutParameter(3, Types.VARCHAR);
			cs.execute();
			return cs.getString(3);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cs != null) {
				try {
					cs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return null;

	}
	
	/**
	 * 获取记录总数
	 */
	public int getCntBySql(String sql){
		return  this.getJdbcTemplate().queryForInt(sql);
	}
	

	@Override
	public Boolean recordOperateLog(String sql) throws Exception {
		int no=0;
		try {
			no= this.jdbcTemplate.update(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
}


